package com.bbg.amyam.web.flow.service.schoolPublicView.createProfile;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import com.bbg.amyam.domain.model.Profile;
import com.bbg.amyam.domain.model.School;
import com.bbg.amyam.process.jms.queue.PasswordResetMessage;
import com.bbg.amyam.process.jms.queue.QueueEventAgent;
import com.bbg.amyam.web.flow.service.WebFlowService;
import com.bbg.amyam.web.util.RequestPathParameter;
import com.bbg.amyam.web.util.RequestPathPaser;



@Service("createProfileService")
public class CreateProfileServiceImpl extends WebFlowService implements CreateProfileService {
	
	@Autowired
	private QueueEventAgent queueEventAgent;
	
	public Event inputEmailAddressAction(RequestContext context) {
		CreateProfileForm form = getForm(context);
		String email = form.getEmail();
		List<Profile> profiles = Profile.findProfilesByEmailEquals(email)
				.getResultList();
		if (profiles.size() < 1) {
			return success();
		} else {
			return error();
		}
	}

	public Event inputProfileDetailAction(RequestContext context) {
		CreateProfileForm form = getForm(context);
		Profile profile = form.toObject();
		try {
			profile.persist();
			form.setMessage("Profile created");
			School school=loadCurrentSchool();
			RequestPathParameter param=RequestPathPaser.parse((HttpServletRequest)context.getExternalContext().getNativeRequest());
			PasswordResetMessage queueMessage=new PasswordResetMessage();
			queueMessage.setProfileId(profile.getId());
			queueMessage.setSchoolShortName(school.getShortName());
			queueMessage.setRequestURL(param.getRequestURL());
			queueEventAgent.sendMessage(queueMessage);
			return success();
		} catch (Exception e) {
			form.setMessage(e.getMessage());
			return error();
		}
	}
	
	private CreateProfileForm getForm(RequestContext context) {
		return (CreateProfileForm) context.getFlowScope()
				.get("createProfileForm");
	}
}
